import axios from "@/axios"
import { loginStatus } from '@/stores/counter'

import { jwtDecode } from 'jwt-decode';
// 扩展接口
interface JwtPayload {
    id: string;
}

const login_status = loginStatus();

async function login(data: { name: string, password: string }): Promise<string> {
    console.log("try login: " + JSON.stringify(data));
    try {
        const response = await axios.post('/login', data);
        // 处理请求成功的响应
        console.info('Login successful:', response);
        // 读取 token
        let token = response.data.token;
        // 储存 token
        login_status.setupToken(token);
        // 解析 token
        const parsedToken: JwtPayload = jwtDecode(token)
        console.log(parsedToken);
        // 获取用户信息
        const userInfo = await getUserById(parsedToken.id)
        // 登录
        login_status.login({ id: parsedToken.id, ...userInfo });
        return String(token);
    } catch (error) {
        // 处理登录失败的情况
        window.$utils.message.error('登录错误：' + error);
        console.error('Login error:', error);
        throw error; // 将错误抛出，以便在调用时可以捕获
    }
}

async function getUserById(id: string): Promise<any> {
    try {
        const response = await axios.get(`/users/${id}`,);
        return response.data;

    } catch (error) {
        console.error('getUserById', error);
        throw error;
    }
}


function initAccount(token: string): void {
    // 包装接口
    login_status.login(token);
}

async function register(data: { name: string, nickname: string, password: string }): Promise<string> {
    console.info("try register: " + data);
    try {
        const response = await axios.post('/register', data);
        // 读取 token
        let token = response.data.token;
        // 储存 token
        login_status.setupToken(token);
        // 解析 token
        const parsedToken: JwtPayload = jwtDecode(token)
        console.log(parsedToken);
        // 获取用户信息
        const userInfo = await getUserById(parsedToken.id)
        // 登录
        login_status.login({ id: parsedToken.id, ...userInfo });
        return String(token);
    } catch (error) {
        console.error('Error during POST request:', error);
        return '';
    }
}

function logout() {
    console.info("logout!");
    login_status.isLogin = false;
}


export default { login, register, logout, getUserById };